package com.example.juc.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Tickets {

    public static void main(String[] args) {

        //Ticket ticket = new Ticket();  //synchronized
        Ticket1 ticket = new Ticket1();  //lock

        new Thread(() -> {
            for (int i = 0; i < 500; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 500; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 500; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

class Ticket {

    private Integer num = 500;

    public synchronized void sale() {

        if (num > 0) {
            System.out.println("线程：" + Thread.currentThread().getName() + "卖出了第" + (500 - (--num)) + "张票，还剩余" + num + "张票。");
        }

    }

}

class Ticket1 {

    private Integer num = 500;

    Lock lock = new ReentrantLock();

    public synchronized void sale() {

        lock.lock();

        try {
            if (num > 0) {
                System.out.println("线程：" + Thread.currentThread().getName() + "卖出了第" + (500 - (--num)) + "张票，还剩余" + num + "张票。");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            lock.unlock();
        }

    }

}
